package controller

import (
	"context"
	"fmt"
	"strings"

	v1 "mygf2/api/v1"
	"mygf2/internal/service"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
)

var (
	Video = cVideo{}
)

type cVideo struct{}

//下载到本地并上传到oss
func (c *cVideo) Download(ctx context.Context, req *v1.GatherDownReq) (res *v1.Res, err error) {
	if req.Ids == nil {
		g.RequestFromCtx(ctx).Response.WriteJsonExit(g.Map{
			"code":    -1,
			"message": "缺少参数",
			"data":    req.Ids,
		})
	}
	taskChan := make(chan bool) //任务通道
	for _, id := range req.Ids {
		go service.GatherUrls().GatherDownload(ctx, id, taskChan)
	}
	success := 0
	for i := 0; i < len(req.Ids); i++ {
		suc := <-taskChan
		if suc {
			success++
		}
	}
	message := fmt.Sprintf("共处理%d条数据，成功%d条", len(req.Ids), success)
	g.RequestFromCtx(ctx).Response.WriteJsonExit(g.Map{
		"code":    0,
		"message": message,
		"data":    req.Ids,
	})
	return
}

//传到正式数据库
func (c *cVideo) InStorage(ctx context.Context, req *v1.GatherInStorageReq) (res *v1.Res, err error) {

	if req.Ids == nil {
		g.RequestFromCtx(ctx).Response.WriteJsonExit(g.Map{
			"code":    -1,
			"message": "缺少参数",
			"data":    req.Ids,
		})
	}
	taskChan := make(chan bool) //任务通道
	for _, id := range req.Ids {
		go service.GatherUrls().GatherInStorage(ctx, id, taskChan)
	}
	success := 0
	for i := 0; i < len(req.Ids); i++ {
		suc := <-taskChan
		if suc {
			success++
		}
	}
	message := fmt.Sprintf("共处理%d条数据，成功%d条", len(req.Ids), success)
	g.RequestFromCtx(ctx).Response.WriteJsonExit(g.Map{
		"code":    0,
		"message": message,
		"data":    req.Ids,
	})
	return
}
func (c *cVideo) GetItem(ctx context.Context, req *v1.GatherInfoReq) (res *v1.Res, err error) {
	if req.Id == 0 {
		g.RequestFromCtx(ctx).Response.WriteJsonExit(g.Map{
			"code":    -1,
			"message": "缺少参数",
			"data":    "",
		})
	}
	gatherUrls := service.GatherUrls().GetInfo(ctx, req.Id)
	if gatherUrls == nil {
		g.RequestFromCtx(ctx).Response.WriteJsonExit(g.Map{
			"code":    -1,
			"message": "未找到数据",
			"data":    "",
		})
	}
	g.RequestFromCtx(ctx).Response.WriteJsonExit(g.Map{
		"code":    0,
		"message": "获取成功",
		"data":    gatherUrls,
	})
	return
}
func (c *cVideo) GetList(ctx context.Context, req *v1.GatherListParamReq) (res *v1.Res, err error) {
	where := g.Map{}
	if req.Source != "" {
		where["source"] = req.Source
	}
	if req.Title != "" {
		where["title like ?"] = "%" + req.Title + "%"
	}
	if req.StartGatherdate != "" {
		//检验下格式
		if t, err := gtime.StrToTime(req.StartGatherdate); err == nil {
			//fmt.Println(t.Format("Y-m-d H:i:s"))
			where["create_at >="] = t.Format("Y-m-d H:i:s")
		}

	}
	if req.EndGatherdate != "" {
		//检验下格式
		if t, err := gtime.StrToTime(req.EndGatherdate); err == nil {
			//fmt.Println(t.Format("Y-m-d H:i:s"))
			where["create_at <"] = t.AddDate(0, 0, 1).Format("Y-m-d H:i:s")
		}

	}
	//fmt.Println(where)
	list := service.GatherUrls().GetList(ctx, where, req.Page, req.Pagesize)
	g.RequestFromCtx(ctx).Response.WriteJsonExit(g.Map{
		"code":    0,
		"message": "获取成功",
		"data":    list,
	})
	return
}
func (c *cVideo) GetListCount(ctx context.Context, req *v1.GatherListCountParamReq) (res *v1.Res, err error) {
	where := g.Map{}
	if req.Source != "" {
		where["source"] = req.Source
	}
	if req.Title != "" {
		where["title like ?"] = "%" + req.Title + "%"
	}
	if req.StartGatherdate != "" {
		//检验下格式
		if t, err := gtime.StrToTime(req.StartGatherdate); err == nil {
			//fmt.Println(t.Format("Y-m-d H:i:s"))
			where["create_at >="] = t.Format("Y-m-d H:i:s")
		}

	}
	if req.EndGatherdate != "" {
		//检验下格式
		if t, err := gtime.StrToTime(req.EndGatherdate); err == nil {
			//fmt.Println(t.Format("Y-m-d H:i:s"))
			where["create_at <"] = t.AddDate(0, 0, 1).Format("Y-m-d H:i:s")
		}

	}
	//fmt.Println(where)
	count := service.GatherUrls().GetListCount(ctx, where)
	g.RequestFromCtx(ctx).Response.WriteJsonExit(g.Map{
		"code":    0,
		"message": "获取成功",
		"data":    count,
	})
	return
}
func (c *cVideo) GetSourceList(ctx context.Context, req *v1.VedioSourceReq) (res *v1.Res, err error) {
	g.RequestFromCtx(ctx).Response.WriteJsonExit(g.Map{
		"code":    0,
		"message": "获取成功",
		"data":    service.VideoSourceMap,
	})
	return
}

func (c *cVideo) DouyinByAuthor(ctx context.Context, req *v1.GatherDouyinByAuthorReq) (res *v1.Res, err error) {
	gatherService, ok := service.ServiceMapper["douyin"]
	if !ok {
		g.RequestFromCtx(ctx).Response.WriteJsonExit(g.Map{
			"code":    -1,
			"message": "出错了",
			"data":    "",
		})
		return
	}
	data := gatherService.GatherByAuthor(ctx, req.Urls)
	g.RequestFromCtx(ctx).Response.WriteJsonExit(g.Map{
		"code":    0,
		"message": "分析成功",
		"data":    data,
	})
	return
}
func (c *cVideo) AnalysisUrl(ctx context.Context, req *v1.AnalysisUrlReq) (res *v1.Res, err error) {
	temp_urls := strings.Replace(req.Urls, "\r\n", "\n", -1)
	temp_urls = strings.Replace(temp_urls, "\r", "\n", -1)
	urls := strings.Split(temp_urls, "\n")
	if _, ok := service.VideoSourceMap[req.Source]; !ok {
		g.RequestFromCtx(ctx).Response.WriteJsonExit(g.Map{
			"code":    -1,
			"message": "来源参数不正确",
			"data":    "",
		})
		return
	}
	var data []interface{}
	var gatherService service.GatherService
	taskChan := make(chan interface{}) //任务通道
	taskUrlCount := make([]string, 0)  //任务数
	//taskResChan := make(chan interface{}) //结果通道
	if req.Source != "auto" {
		gatherService, ok := service.ServiceMapper[req.Source]
		if !ok {
			g.RequestFromCtx(ctx).Response.WriteJsonExit(g.Map{
				"code":    -1,
				"message": "来源参数不正确",
				"data":    "",
			})
			return
		}
		for _, url := range urls {
			if url != "" {
				go gatherService.Fetch(ctx, url, taskChan)
				//data = append(data, temp_res)
				taskUrlCount = append(taskUrlCount, url)
			}
		}

	} else {
		//根据链接获取对象
		for _, url := range urls {
			if url != "" {
				for _, sev := range service.ServiceMapper {
					gatherService = sev
					temp_var := gatherService.GetUrl(url)
					//fmt.Println(temp_var)
					if temp_var != "" {
						go gatherService.Fetch(ctx, temp_var, taskChan)
						taskUrlCount = append(taskUrlCount, temp_var)
						//data = append(data, temp_res)
					}
				}

			}
		}

	}
	for i := 0; i < len(taskUrlCount); i++ {
		taskRes := <-taskChan
		if taskRes != nil {
			data = append(data, taskRes)
		}
	}
	g.RequestFromCtx(ctx).Response.WriteJsonExit(g.Map{
		"code":    0,
		"message": "分析成功",
		"data":    data,
	})
	return
}
